<?php
/**
 * Created by PhpStorm.
 * User: admin
 * Date: 2019/4/14
 * Time: 9:53
 */

namespace service\excel\purchase;
use app\storage\common\Template;
use app\storage\model\StorageModel;
use app\storage\service\MaterielService;
use app\storage\service\SupplierService;
use service\excel\AbstractExcel;
use think\Config;
use think\Db;

class Purchase extends AbstractExcel
{

    public function __construct()
    {
        parent::__construct();
        $this->config = Config::get('purchase_excel');
    }

    public function getData()
    {
        $reader = $this->phpReader->load($this->path);
        $sheet = $reader->getSheet(0);//获取第一个工作区
        $purchaseId = trim($sheet->getCell($this->config['purchase_id'])->getValue());//获取purchase的数据
        $this->tableData['storageName'] = trim($sheet->getCell($this->config['storage'])->getValue());//获取purchase的数据的数据
        $this->tableData['purchaseId'] = empty($purchaseId) ? create_unique_id('POORD') : $purchaseId;
        $this->tableData['remark'] = trim($sheet->getCell($this->config['remark'])->getValue());//获取remark的数据
        $highestColumn = $sheet->getHighestRow(); //取得总行数，为接下里获取数据准备
        $reels = [];//专门用来记录reel_id 是为了判断这个excel里的reel_id有没有在库中
        for ($i = $this->config['data_begin']; $i <= $highestColumn; $i++) {//从配置中读书数据从哪行开始读取数据
            $reel = trim($sheet->getCell($this->config['reel_id'] . $i)->getValue());
            if (empty($reel)) {//防止空行，如果取不到数据了就跳出
                break;
            }
            $reels[] = $reel;
            $this->tableData['reels'][] = [
                'sub_materiel_id' => strtoupper(trim($sheet->getCell($this->config['sub_materiel_id'] . $i)->getValue())),
                'reel_id' => $reel,
                'count' => trim($sheet->getCell($this->config['count'] . $i)->getValue()),
                'supplier_id'=> trim($sheet->getCell($this->config['supplier_id'] . $i)->getValue()),
            ];
        }
    }

    public function checkData()
    {
        $this->getData();
        if (empty($this->tableData['reels'])) {
            return ret_template(false, '表格中入库的数据为空');
        }
        $storageModel = new StorageModel();
        $this->tableData['storageUuid'] = $storageModel->where(['name' => $this->tableData['storageName']])->value('uuid');
        if (empty($this->tableData['storageUuid'] )) {
            return ret_template(false, "仓库{$this->tableData['storageName']}不存在");
        }
        preg_match('/\w[A-z]+/', $this->tableData['purchaseId'], $match);//解析开头的字符
        if (!in_array($match[0], $this->config['allow_pre'])) {//判断是不是在允许的开头里面
            return ret_template(false, '采购单号格式不对');
        }
        $materielExcel = array_unique(array_column($this->tableData['reels'], 'sub_materiel_id'));
        $materiel = MaterielService::create_materiel($materielExcel);
        if ($materiel['success'] === false) {
            return $materiel;
        }
        $supplierList = array_unique(array_column($this->tableData['reels'], 'supplier_id'));
        $supplier = SupplierService::create_supplier($supplierList);
        if ($supplier['success'] === false) {
            return $supplier;
        }
        $repeat = Db::table('iwh_purchase')->where('purchase_id', $this->tableData['purchaseId'])->find();
        if (count($repeat)) {
            return ret_template(false, "单号{$this->tableData['purchaseId']}已存在");
        }
        $reelId = array_unique(array_column($this->tableData['reels'], 'reel_id'));
        foreach ($reelId as $i => $value) {
            $strLen = strlen($value);
            if ($strLen != 17) {
                $error[] = $i + 4;
            }
        }
        if (!empty($error)) {
            $error = implode('、', $error);
        }
        if (!empty($error)) {
            return ret_template(false, '第' . $error . '行条码错误');
        }
        return ret_template(true, '数据正确');
    }

    public function insertToDb()
    {
        $reels = $this->tableData['reels'];
        $purchase = Template::purchaseTemplate($this->tableData['purchaseId'],$this->tableData['storageUuid'],$this->tableData['remark']);
        foreach ($reels as $item) {
            $purchaseDetail[] = Template::purchaseDetailTemplate($item['reel_id'], $item['sub_materiel_id'], $item['count'], $this->tableData['purchaseId'],$item['supplier_id']);
        }

        Db::startTrans();
        $tranDet = $tranSub = $tranSup = $tranPur = true;
        $tranPur = Db::table('iwh_purchase')->insert($purchase);

        if (!empty($purchaseDetail)) {
            $tranDet = Db::table('iwh_purchase_detail')->insertAll($purchaseDetail, true);
        }
        if ($tranPur && $tranDet) {
            Db::commit();
            return ret_template(true, '上传成功');
        } else {
            Db::rollback();
            return ret_template(false, '上传失败');
        }
    }
}